<template>
    <el-card shadow="hover">
        <template #header>
            <div class="file-manager-header">
                <div class="file-path">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item
                                v-for="(path, index) in filePath"
                                :key="index"
                                @click="navigateToPath(index)"
                                style="cursor: pointer"
                        >
                            {{ path }}
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </div>

                <div class="file-actions">
                    <el-button style="margin: 0" type="primary" icon="refresh" @click="getFileList">刷新</el-button>
                    <el-button style="margin: 0" type="primary" icon="Upload" @click="triggerUpload"> 上传文件
                    </el-button>
                    <!-- 隐藏的文件输入 -->
                    <input
                            type="file"
                            ref="fileInput"
                            @change="handleFileUpload"
                            style="display: none"
                            webkitdirectory
                            directory
                            multiple
                    />

                    <el-button
                            type="primary"
                            icon="FolderAdd"
                            @click="createFolder"
                            :disabled="filePath.length >= 5"
                    >
                        新建文件夹
                    </el-button>

                    <el-button style="margin: 0" type="primary" icon="Upload" @click="uploadFile"> 发送文件</el-button>
                    <el-button style="margin: 0" icon="Back" @click="goToParentDirectory"
                               :disabled="filePath.length <= 1">
                        返回上级
                    </el-button>

                </div>
            </div>
        </template>

        <el-table
                ref="fileTable"
                :data="tableModal.dataSource"
                v-loading="tableModal.loading"
                border
                style="width: 100%"
                @selection-change="tableModal.handleFileSelectionChange"
                row-key="name"
                :fit="true"
        >
            <el-table-column type="selection" width="50"/>
            <el-table-column prop="name" label="文件名" min-width="300">
                <template #default="scope">
                    <div class="file-item" style="cursor:pointer" @click.prevent="tableModal.handleFileClick(scope.row)">
                        <el-icon :size="18" :color="scope.row.type === 'directory' ? '#409EFF' : '#67C23A'">
                            <component :is="scope.row.type === 'directory' ? 'Folder' : 'Document'"/>
                        </el-icon>
                        <span class="file-name" style="cursor: pointer">{{ scope.row.name }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="120">
                <template #default="scope">
                    <el-tag :type="scope.row.type === 'directory' ? 'primary' : 'success'">
                        {{ scope.row.type === 'directory' ? '文件夹' : '文件' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="size" label="大小" width="120"/>
            <el-table-column label="操作" width="160">
                <template #default="scope">
                    <el-button link size="small" icon="Edit" @click="handleDirEdit(scope.row,false)"> 修改</el-button>
                    <a-modal :width="editDirModel.width" title="修改文件夹名称"
                             :open="editDirModel.open" :ok-button-props="{loading:editDirModel.loading}"
                             @ok="handleDirEdit(scope.row,true)"
                    >
                        <a-form :model="editDirModel.form">
                            <a-form-item label="新文件夹名称">
                                <a-input
                                        v-model:value="editDirModel.form.newDirName"
                                        placeholder="请输入新文件夹名称"
                                />
                            </a-form-item>
                        </a-form>
                    </a-modal>
                    <el-button
                            link
                            size="small"
                            icon="Delete"
                            style="color: #f56c6c"
                            @click="handleDirDelete"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 发送文件对话框 -->
        <el-dialog
                v-model="uploadModel.visible"
                title="选择接收用户"
                width="600px"
                :close-on-click-modal="false"
        >
            <el-table
                    ref="userTable"
                    :data="uploadModel.dataSource"
                    v-loading="uploadModel.loading"
                    border
                    style="width: 100%"
                    @selection-change="uploadModel.handleSelectionChange"
            >
                <el-table-column type="selection" width="50"/>
                <el-table-column prop="username" label="用户账号" width="250"/>
                <el-table-column prop="realName" label="用户名称" width="300"/>
            </el-table>
            <template #footer>
                <el-button @click="uploadModel.visible = false">取消</el-button>
                <el-button type="primary" @click="confirmSendFile">发送</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import {computed, h, reactive, ref} from 'vue'
import {postAction} from '@/request/request'
import {adminUrl, userUrl} from '@/api/api'
import {ElLoading, ElMessage} from 'element-plus'
import {API_BASE_URL} from '@/config'
import {useUserStore} from '@/store/user'
import {ReloadOutlined} from '@ant-design/icons-vue'
import {Modal} from "ant-design-vue";

const filePath = ref(['Admin'])
const user = computed(() => {
    return useUserStore().user
})
const handleFileUpload = async event => {
    tableModal.loading = true
    const files = Array.from(event.target.files)
    if (files.length === 0) return

    // 检查文件大小
    const maxSize = 5 * 1024 * 1024 * 1024 // 5GB
    const oversizedFiles = files.filter(file => file.size > maxSize)

    if (oversizedFiles.length > 0) {
        ElMessage.error(`以下文件超过5GB限制: ${oversizedFiles.map(f => f.name).join(', ')}`)
        event.target.value = '' // 重置输入
        return
    }

    const currentPath = filePath.value.join('/')
    const uploadData = {
        currentPath: currentPath,
        username: user.username,
        files: []
    }

    // 将每个文件转换为Base64
    for (const file of files) {
        const base64String = await new Promise((resolve, reject) => {
            const reader = new FileReader()
            reader.onload = () => resolve(reader.result.split(',')[1]) // 去掉data:前缀
            reader.onerror = error => reject(error)
            reader.readAsDataURL(file)
        })

        uploadData.files.push({
            relativePath: file.webkitRelativePath.replace(file.name, ''),
            name: file.name,
            data: base64String
        })
    }

    // 使用fetch发送JSON数据

    postAction(adminUrl.upload, uploadData,{
        timeout: 0,
    }).then(res => {
        if (res.code === 200) {
            ElMessage.success(`成功上传 ${files.length} 个文件`)
        } else {
            ElMessage.error(res.message)
        }
    }).finally(() => {
        tableModal.loading = false
        event.target.value = '' // 重置输入
        getFileList()
    })

}

const createFolder = () => {
    ElMessage({
        message: '功能暂未开放',
        type: 'warning',
        duration: 3000
    })
}

const uploadFile = () => {
    uploadModel.visible = true
    uploadModel.loading = true

    postAction(userUrl.list, {username: ''})
        .then(response => {
            if (response.code !== 200) {
                ElMessage.error({
                    message: response.message,
                    type: 'error',
                    duration: 3000
                })
            } else {
                // 过滤掉管理员
                uploadModel.dataSource = response.data.filter(item => item.idType !== 0)
            }
        }).finally(() => {
        uploadModel.loading = false
    })
}

const selectedFiles = ref([])
const tableModal = reactive({
    loading: false,
    dataSource: [],
    handleFileClick: row => {
        if (row.type === 'directory') {
            filePath.value.push(row.name)
            getFileList()
        }
    },
    handleFileSelectionChange: selection => {
        selectedFiles.value = selection
    }
})
const editDirModel = reactive({
    open: false,
    width:400,
    form: {
        newDirName: '',
    },
    loading: false,
})
const handleDirEdit = (row,isOk) => {
    editDirModel.open = true
    if (isOk){
        editDirModel.loading = true
        postAction(adminUrl.updateFolderName,{
            path: filePath.value.join(','),
            oldFolderName: row.name,
            newFolderName: editDirModel.form.newDirName
        }).then(res => {
            if (res.code === 200) {
                ElMessage.success('文件夹名称修改成功')
                editDirModel.open = false
                getFileList()
            }else{
                ElMessage.error(res.message)
            }
        }).finally(() => {
            editDirModel.loading = false
            editDirModel.form.newDirName = ''
        })
    }
}

const handleDirDelete = () => {
    ElMessage({
        message: '功能暂未开放',
        type: 'warning',
        duration: 3000
    })
}

const fileInput = ref(null)
const triggerUpload = () => {
    fileInput.value.click()
}
const navigateToPath = index => {
    filePath.value = filePath.value.slice(0, index + 1)
    getFileList()
}
const getFileList = async () => {
    tableModal.loading = true

    postAction(adminUrl.getFileList, {
        path: filePath.value ? filePath.value.join(',') : 'Admin'
    })
        .then(res => {
            if (res.code !== 200) {
                ElMessage.error({
                    message: res.message,
                    type: 'error',
                    duration: 3000
                })
            } else {
                tableModal.dataSource = res.data
            }
        })
        .finally(() => {
            tableModal.loading = false
        })
}
const selectedUsers = ref([])
const uploadModel = reactive({
    visible: false,
    loading: false,
    dataSource: [],
    handleFileClick: row => {
        if (row.type === 'directory') {
            filePath.value.push(row.name)
            getFileList()
        }
    },
    handleSelectionChange: selection => {
        selectedUsers.value = selection
    }
})
const confirmSendFile = async () => {
    if (selectedUsers.value.length === 0) {
        ElMessage.warning('请至少选择一个用户')
        return
    }

    if (selectedFiles.value.length === 0) {
        ElMessage.warning('请至少选择一个文件')
        return
    }

    const fileNames = selectedFiles.value.map(file => file.name).join(',')
    const filePaths = filePath.value.map(part => part).join(',')

    const dataToSend = {
        users: selectedUsers.value.map(user => user.username).join(','),
        fileNames,
        filePaths
    }

    try {
        const response = await fetch(`${API_BASE_URL}/SendFile`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(dataToSend)
        })

        if (!response.ok) {
            throw new Error('网络响应失败')
        }

        const result = await response.json()
        if (result.code === 200) {
            ElMessage.success(`文件已发送给 ${selectedUsers.value.length} 个用户`)
            uploadModel.visible = false
        } else {
            ElMessage.error(result.message || '发送失败')
        }
    } catch (error) {
        ElMessage.error(`发送失败: ${error.message}`)
    }
}
const goToParentDirectory = () => {
    if (filePath.value.length > 1) {
        filePath.value.pop()
        getFileList()
    }
}

defineExpose({
    getFileList
})
</script>

<style scoped>
.file-manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.file-actions {
    display: flex;
    justify-content: space-between;
    gap: 10px;
}

.file-row {
    cursor: pointer;
}
</style>
